rm(list = ls())

wd <- ".../Replication/"
setwd(wd)

# Load/install packages --
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  foreign, 
  ggplot2, 
  estimatr,
  texreg,
  xtable,
  fastDummies,
  sandwich,
  dplyr,
  janitor, 
  gridExtra,
  gsheet,
  zoo,
  interflex,
  lubridate,
  tidyverse,
  stringi,
  readxl,
  ri2,
  modelsummary,
  ggpubr
)

options(scipen=999)

# Note: given the random component inherent to the randomization tests performed
# by ri(), you may observe small differences in the p-values of the randomization
# tests performed using that function.

# Load data ----
d <- read.csv("Data/baseline database.csv")
data <- subset(d, d$group!="Liberado por eleccion")


ITT_mechs <- list()

ITT_mechs[['Robbery']] <- with(data, lm_robust(robbery~lottery_winner))
ITT_mechs[['Assault']] <- with(data, lm_robust(assault~lottery_winner))
ITT_mechs[['Discretionary']] <- with(data, lm_robust(discretionary~lottery_winner))

modelsummary(ITT_mechs, stars = T, output = "latex")

declare <- declare_ra(N = nrow(data), m=sum(data$lottery_winner)) 
ri_mechs <- list()
ri_mechs[['Robbery']] <- summary(conduct_ri(formula = robbery ~ lottery_winner,
                                            declaration = declare,sharp_hypothesis = 0,
                                            assignment = "lottery_winner",
                                            data = data,sims = 10000
))


ri_mechs[['Assault']] <- summary(conduct_ri(
  formula = assault ~ lottery_winner,
  declaration = declare,
  sharp_hypothesis = 0,
  assignment = "lottery_winner",
  data = data,
  sims = 10000
))


ri_mechs[['Discretionary']] <- summary(conduct_ri(
  formula = discretionary ~ lottery_winner,
  declaration = declare,
  sharp_hypothesis = 0,
  assignment = "lottery_winner",
  data = data,
  sims = 10000
))

# make table
Table_A1<-modelsummary(ITT_mechs, stars = T, output = "dataframe")
Table_A1$part<-NULL
Table_A1[nrow(Table_A1)+1,1]<-'Exact p-value'
Table_A1[nrow(Table_A1),'Robbery']<-ri_mechs[['Robbery']][,"two_tailed_p_value"]
Table_A1[nrow(Table_A1),'Assault']<-ri_mechs[['Assault']][,"two_tailed_p_value"]
Table_A1[nrow(Table_A1),'Discretionary']<-ri_mechs[['Discretionary']][,"two_tailed_p_value"]

Table_A1

print(xtable(Table_A1), file = "Output/Table A1.tex")
